package com.github.prontera.common.filter;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.github.prontera.common.auth0.jwt.TokenGenerator;
import com.github.prontera.common.auth0.jwt.interfaces.Claim;
import com.github.prontera.util.CookieManager;

public class CurrentUserMobileArgumentResolver implements HandlerMethodArgumentResolver {

	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterAnnotation(CurrentUserMobile.class) != null;
	}

	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory)
			throws Exception {
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		String token = request.getHeader(MagicConstants.AUTH_TOKEN);
		if (StringUtils.isEmpty(token)) {
			token = request.getParameter(MagicConstants.AUTH_TOKEN);
		}
		if (StringUtils.isEmpty(token)) {
			token = new CookieManager(request, null).getCookie(MagicConstants.AUTH_TOKEN);
		}
		if (!StringUtils.isEmpty(token)) {
			Map<String, Claim> datas = TokenGenerator.getClaims(token);
			String mobile = datas.get(MagicConstants.SESSION_USER_MOBILE).asString();
			return mobile;
		}
		return null;
	}

}